package sdufe.lele.Interceptor;

import com.alibaba.fastjson.JSON;
import org.apache.shiro.util.ThreadContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import sdufe.lele.annotation.authToken;
import sdufe.lele.result.ApiError;
import sdufe.lele.service.RedisDateTimeService;
import sdufe.lele.uitl.Constant;
import sdufe.lele.uitl.Token;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;


/**
 * Created by zhnh9 on 4/9/2017.
 */
@Component
public class ApiAuthenticating extends HandlerInterceptorAdapter {

    @Resource
    private RedisDateTimeService redisDateTimeService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        authToken annotation = method.getAnnotation(authToken.class);

        if (annotation != null) {

            //获取验证身份的token
            String authHeader = request.getParameter(Constant.Authorization);

            if (!StringUtils.isEmpty(authHeader)) {
                //解密token，获得账号密码
                HashMap<String, String> tokenMap = Token.decryptToken(authHeader);
                if (tokenMap == null) {
                    (response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write(JSON.toJSONString(new ApiError("Illegal token", 401)));
                    return false;
                }

                String userphone = tokenMap.get("userphone");

                if (userphone == null) {
                    (response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write(JSON.toJSONString(new ApiError("Illegal token", 401)));
                    return false;
                }

                if (!redisDateTimeService.isExistKey(userphone)){
                    (response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write(JSON.toJSONString(ApiError.unAuthenticate()));
                    return false;
                }
                //查询redis数据库
                LocalDateTime lastTime = redisDateTimeService.searchByKey(userphone);

                if (lastTime == null) {

                    (response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    response.getWriter().write(JSON.toJSONString(ApiError.unAuthenticate()));
                    return false;
                }

                LocalDateTime now = LocalDateTime.now();

                LocalDateTime newtime = null;
                if (tokenMap.get("rem-pass").equals("yes")) {
                    // 现在时间加上7天（记住密码）
                    newtime = now.plusDays(7);
                } else {
                    // 现在时间加上30分钟（不记住密码）
                    newtime = now.plusMinutes(30);
                }

                // 过期重定向到登录页


                if (Duration.between(lastTime, newtime).toMinutes() < 0) {
                    (response).setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
                    response.sendRedirect("../pages/login.html");
                    return false;
                }
                //更新时间
                redisDateTimeService.updateByKey(userphone, newtime);

                ThreadContext.put("user-phone", userphone);

                return true;
            } else {
                (response).setStatus(HttpServletResponse.SC_FORBIDDEN);
                response.getWriter().write(JSON.toJSONString(ApiError.unAuthenticate()));
                return false;
            }
        }
        return true;
    }
}
